package com.flashcash.kotlin.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.location.Address
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.BaseAdapter
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import com.flashcash.kotlin.activity.BackPressListener
import com.flashcash.kotlin.data.SysDict
import com.flashcash.kotlin.data.SysDictBean
import com.flashcash.kotlin.utils.FirebaseAnalyticsConstants
import com.flashcash.kotlin.utils.FirebaseAnalyticsUtils
import com.flashcash.kotlin.widget.LocalButton
import com.flashcash.kotlin.widget.LocalEditText
import com.flashcash.solu.BuildConfig
import com.flashcash.solu.R
import com.flashcash.solu.app.base.BaseFragment
import com.flashcash.solu.app.base.presenter.BaseFragmentPresenter
import com.flashcash.solu.app.base.presenter.BaseFragmentPresenterImpl
import com.flashcash.solu.bean.PersonalInfoBean
import com.flashcash.solu.bean.PersonalInfoServerBean
import com.flashcash.solu.bean.RegionBean
import com.flashcash.solu.bean.ResponseErrorBody
import com.flashcash.solu.common.EventCollection
import com.flashcash.solu.common.FieldParams
import com.flashcash.solu.common.FieldParamsInt
import com.flashcash.solu.common.TokenManager
import com.flashcash.solu.common.adapter.InfoAdapter
import com.flashcash.solu.common.adapter.InfoAdapterEnum
import com.flashcash.solu.utils.ACache
import com.flashcash.solu.view.IntroduceActivity
import com.flashcash.solu.view.certification.ContactInfoActivity
import com.flashcash.solu.view.certification.PersonalInfoActivity
import com.flashcash.solu.view.certification.status.*
import com.flashcash.solu.widget.MyEditTextView
import com.flashcash.solu.widget.SelectView
import com.flashcash.solu.widget.selfdefdialog.DialogManager
import com.flashcash.solu.widget.stepview.HorizontalStepView
import com.flashcash.solu.widget.stepview.bean.StepBean
import com.flashcash.solu.widget.xleotoast.XLeoToast
import com.google.gson.Gson
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.jakewharton.rxbinding.widget.RxTextView
import com.x.leo.apphelper.data.cache.CacheDataManage
import com.x.leo.apphelper.log.XLog
import okhttp3.ResponseBody
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.support.v4.toast
import retrofit2.adapter.rxjava.HttpException
import rx.Observable
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

/**
 * @作者:XLEO
 * @创建日期: 2017/8/14 10:01
 * @描述:${TODO}
 *
 * @更新者:${Author}$
 * @更新时间:${Date}$
 * @更新描述:${TODO}
 * @下一步：
 */
class PersonalInfoFragment : BaseFragment<PersonalInfoPresenter>(), PersonalInfoView, BackPressListener {
    override fun finish(): Boolean {
        return !notFinish
    }

    override fun onUploadedSuccess() {
        FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_PERSONAL_INFO_SUBMIT_SUCCESS, null)
        removeAllLocal()
    }

    override fun onBackPressed() {
        if (localInputExist() && !identicalToServer()) {

            saveLocalInput()

            toast(this.getString(R.string.change_not_upload))
        } else {
            removeThisPageLocal()
        }
        if (fromSplash) {
            startActivity(Intent(baseActivity, IntroduceActivity::class.java))
        }
    }

    companion object {
        private const val SAVE_INSTANCE_IS_EDITABLE = "save_instance_is_editable"
        private const val SAVE_INSTANCE_HAS_SAVED_STATE = "save_instance_has_save_state"
    }

    private var firstName: String = ""
    private var middleName: String = ""
    private var lastName: String = ""
    private var birthday: String = ""
    private var cardType: String = ""
    private var fullName: String = ""
    private var ktpno: String = ""
    private var gender: String = ""
    //    private lateinit var fullName: LocalTextView
//    private lateinit var ktpno: LocalTextView
//    private lateinit var gender: LocalTextView
    private lateinit var education: SelectView
    private lateinit var marital: SelectView
    private lateinit var childrenAccount: SelectView
    private lateinit var region: SelectView
    private lateinit var address: MyEditTextView
    private lateinit var duration: SelectView
    private lateinit var pInfoSummit: LocalButton
    private lateinit var dialogPlus: Dialog

    var personalInfoBean: PersonalInfoBean = PersonalInfoBean()
//    private lateinit var mTvPersonalInfoFacebookId: TextView

    private var hasSavedState: Boolean = false


    private lateinit var familyNameInLaw: LocalEditText
    private lateinit var facebookAccount: MyEditTextView


    private val mRequestCode = 1222

    private var isEditable: Boolean = false

    override fun doPreBuildHeader(): Boolean {
        return true
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putCharSequence(FieldParams.PersonInfo.FULLNAME, fullName)
        outState.putCharSequence(FieldParams.PersonInfo.FIRSTNAME, firstName)
        outState.putCharSequence(FieldParams.PersonInfo.MIDDLENAME, middleName)
        outState.putCharSequence(FieldParams.PersonInfo.LASTNAME, lastName)
        outState.putCharSequence(FieldParams.PersonInfo.CARDTYPE, cardType)
        outState.putCharSequence(FieldParams.PersonInfo.BIRTHDAY, birthday)
        outState.putCharSequence(FieldParams.PersonInfo.KTP_NO, ktpno)
        outState.putCharSequence(FieldParams.PersonInfo.GENDER, gender)
        outState.putCharSequence(FieldParams.PersonInfo.EDUCATION, education.text)
        outState.putCharSequence(FieldParams.PersonInfo.MARITAL, marital.text)
        outState.putCharSequence(FieldParams.PersonInfo.CHILDRENACCOUNT, childrenAccount.text)
        outState.putCharSequence(FieldParams.PersonInfo.REGION, region.text)
        outState.putCharSequence(FieldParams.PersonInfo.PROVINCE, personalInfoBean.province?.name)
        outState.putCharSequence(FieldParams.PersonInfo.DISTRICT, personalInfoBean.district?.name)
        outState.putCharSequence(FieldParams.PersonInfo.CITY, personalInfoBean.city?.name)
        /*outState.putCharSequence(FieldParams.PersonInfo.AREA, personalInfoBean.area?.name)*/
        outState.putCharSequence(FieldParams.PersonInfo.ADDRESS, address.text)
        outState.putCharSequence(FieldParams.PersonInfo.DURATION, duration.text)
        outState.putCharSequence(FieldParams.PersonInfo.FAMILYNAMEINLAW, familyNameInLaw.text.toString())
        outState.putCharSequence(FieldParams.PersonInfo.FACEBOOK_ID, facebookAccount.text.toString())
        outState.putBoolean(SAVE_INSTANCE_IS_EDITABLE, isEditable)
        hasSavedState = true
        outState.putBoolean(SAVE_INSTANCE_HAS_SAVED_STATE, hasSavedState)
        if (BuildConfig.DEBUG) {
            Log.i("PersonalInfoFragment", "onSaveInstanceState isEditable = $isEditable ,hasSavedState = $hasSavedState")
        }
    }


    override fun initHeader(view: TextView?): Boolean {
        view?.setText(R.string.textview_title_personal_info)
        return true
    }

    override fun showMessageIcon(): Boolean {
        return false
    }

    override fun getBackPressListener(): View.OnClickListener {
        return View.OnClickListener {
            if (fromSplash) {
                startActivity(Intent(baseActivity, IntroduceActivity::class.java))
            }
            activity!!.finish()
        }
    }

    override fun initPresenter(): PersonalInfoPresenter {
        return PersonalInfoPresenterImpl()
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_personal_info
    }

    override fun initView(view: View?, savedInstanceState: Bundle?) {
        FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.EXPOSURE_PERSONAL_INFO, null)

        isEditable = CacheDataManage.obtainData(FieldParamsInt.INFO_EDITABLE, Boolean::class.java)
                ?: false
        RxBus.get().register(context)

        //geoRequest();
//        view!!.find<TextView>(R.id.tv_personal).isSelected = true
//        view.find<TimeLineView>(R.id.personal_node).currentStatus = TimeLineView.ACTIVE
        initFind(view!!)
        editTextChangeEvent()
        savedInstanceState?.apply {
            hasSavedState = savedInstanceState[SAVE_INSTANCE_HAS_SAVED_STATE] as Boolean? ?: false
        }
        if (hasSavedState && savedInstanceState != null) {
            initViewByState(savedInstanceState)
        } else {
            initByLocal()
        }
        updateSubmitSate()
        view.find<ScrollView>(R.id.sv).smoothScrollTo(0, 0)
        if (BuildConfig.DEBUG) {
            Log.i("PersonalInfoFragment", "initView isEditable = $isEditable ,hasSavedState = $hasSavedState")
        }
        if (!isEditable) {
            AlertDialog.Builder(context)
                    .setTitle(R.string.tips_title)
                    .setMessage(R.string.cannot_edit_now)
                    .setPositiveButton(R.string.button_ok, { dialog, _ ->
                        dialog.dismiss()
                    })
                    .create()
                    .show()
        }
    }

    @Subscribe
    fun onFinish(event: EventCollection.FirstFinishCertifyEvent) {
        baseActivity.finish()
    }

    private fun initByLocal() {
        val cache = ACache.get(this.baseActivity)

        val nameFromLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.FULLNAME))
        if (!TextUtils.isEmpty(nameFromLocal)) {
            personalInfoBean.fullName = nameFromLocal
            fullName = nameFromLocal
        }

        val firstNameFromLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.FIRSTNAME))
        if (!TextUtils.isEmpty(firstNameFromLocal)) {
            personalInfoBean.firstName = firstNameFromLocal
            firstName = firstNameFromLocal
        }

        val middleNameFromLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.MIDDLENAME))
        if (!TextUtils.isEmpty(middleNameFromLocal)) {
            personalInfoBean.middleName = middleNameFromLocal
            middleName = middleNameFromLocal
        }


        val lastNameFromLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.LASTNAME))
        if (!TextUtils.isEmpty(lastNameFromLocal)) {
            personalInfoBean.lastName = lastNameFromLocal
            lastName = lastNameFromLocal
        }

        val birthdayFromLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.BIRTHDAY))
        if (!TextUtils.isEmpty(birthdayFromLocal)) {
            personalInfoBean.birthday = birthdayFromLocal
            birthday = birthdayFromLocal
        }

        val cardTypeFromLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.CARDTYPE))
        if (!TextUtils.isEmpty(cardTypeFromLocal)) {
            personalInfoBean.credentialType = cardTypeFromLocal
            cardType = cardTypeFromLocal
        }

        val ktpNoFromLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.KTP_NO))
        if (!TextUtils.isEmpty(ktpNoFromLocal)) {
            personalInfoBean.credentialNo = ktpNoFromLocal
            ktpno = ktpNoFromLocal
        }

        val genderFromLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.GENDER))
        if (!TextUtils.isEmpty(genderFromLocal)) {
            gender = GenderStatus.valueOf(genderFromLocal).value
            personalInfoBean.gender = genderFromLocal
        }

        val familyNameInLawLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.FAMILYNAMEINLAW))
        if (!TextUtils.isEmpty(familyNameInLawLocal)) {
            familyNameInLaw.setText(familyNameInLawLocal)
            personalInfoBean.familyNameInLaw = familyNameInLawLocal
        }

        val facebookAccountLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.FACEBOOK_ID))
        if (!TextUtils.isEmpty(facebookAccountLocal)) {
            facebookAccount.text = facebookAccountLocal
            personalInfoBean.facebookId = facebookAccountLocal
        }

        val educationLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.EDUCATION))
        if (!TextUtils.isEmpty(educationLocal)) {
            education.text = educationLocal
            personalInfoBean.lastEducation = educationLocal
        }

        val marriageLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.MARITAL))
        if (!TextUtils.isEmpty(marriageLocal)) {
            marital.setText(MarriageStatus.valueOf(marriageLocal).showString)
            personalInfoBean.maritalStatus = marriageLocal
        }

        val childNumLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.CHILDRENACCOUNT))
        if (!TextUtils.isEmpty(childNumLocal)) {
            childrenAccount.setText(ChildrenNumStatus.valueOf(childNumLocal).showString)
            personalInfoBean.childrenNumber = childNumLocal
        }
//
//        val regionLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.REGION))
//        if (!TextUtils.isEmpty(regionLocal)) {
//            region.text = regionLocal
//        }

        val provinceLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.PROVINCE))
        if (!TextUtils.isEmpty(provinceLocal)) {

            val r = RegionBean.RegionsBean()
            r.name = provinceLocal
            personalInfoBean.province = r
        }

        val cityLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.CITY))
        if (!TextUtils.isEmpty(cityLocal)) {

            val r = RegionBean.RegionsBean()
            r.name = cityLocal
            personalInfoBean.city = r
        }

        val districtLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.DISTRICT))
        if (!TextUtils.isEmpty(districtLocal)) {

            val r = RegionBean.RegionsBean()
            r.name = districtLocal
            personalInfoBean.district = r
        }

        /*val areaLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.AREA))
        if (!TextUtils.isEmpty(areaLocal)) {

            val r = RegionBean.RegionsBean()
            r.name = areaLocal
            personalInfoBean.area = r
        }*/

        val addressLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.ADDRESS))
        if (!TextUtils.isEmpty(addressLocal)) {
            address.text = addressLocal
            personalInfoBean.address = addressLocal
        }

        val residenceLocal = cache.getAsString(getSaveKey(FieldParams.PersonInfo.DURATION))
        if (!TextUtils.isEmpty(residenceLocal)) {
            duration.setText(DurationStatus.valueOf(residenceLocal).showString)
            personalInfoBean.residenceDuration = residenceLocal
        }

        updateRegionInfo()
    }

    private fun initViewByState(state: Bundle) {
        isEditable = state[SAVE_INSTANCE_IS_EDITABLE] as Boolean? ?: false
        if (isEditable) {
            CacheDataManage.addData(FieldParamsInt.INFO_EDITABLE, isEditable)
        }
        fullName = state[FieldParams.PersonInfo.FULLNAME] as String
        firstName = state[FieldParams.PersonInfo.FIRSTNAME] as String
        middleName = state[FieldParams.PersonInfo.MIDDLENAME] as String
        lastName = state[FieldParams.PersonInfo.LASTNAME] as String
        birthday = state[FieldParams.PersonInfo.BIRTHDAY] as String
        cardType = state[FieldParams.PersonInfo.CARDTYPE] as String
        ktpno = state[FieldParams.PersonInfo.KTP_NO] as String
        gender = state[FieldParams.PersonInfo.GENDER] as String
        familyNameInLaw.setText(state[FieldParams.PersonInfo.FAMILYNAMEINLAW] as CharSequence)
        facebookAccount.text = state[FieldParams.PersonInfo.FACEBOOK_ID] as String
        education.text = state[FieldParams.PersonInfo.EDUCATION] as String
        marital.text = state[FieldParams.PersonInfo.MARITAL] as String
        childrenAccount.text = state[FieldParams.PersonInfo.CHILDRENACCOUNT] as String
        region.text = state[FieldParams.PersonInfo.REGION] as String

        duration.text = state[FieldParams.PersonInfo.DURATION] as String
        if (arguments != null) {
            val any = arguments!![FieldParams.NEED_UPDATE_REGION]
            if (any != null && any as Boolean) {
                handleRegionChange()
                arguments!!.putBoolean(FieldParams.NEED_UPDATE_REGION, false)
            }
        }
        address.text = state[FieldParams.PersonInfo.ADDRESS] as String
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initFind(view: View) {
        familyNameInLaw = view.find(R.id.id_edittext_personal_onfo_family_name_in_law)
        facebookAccount = view.find(R.id.id_edittext_personal_facebook_account)
        facebookAccount.setItemOnClickListener {
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.PERSONAL_FACEBOOK_NAME, null)
            val imm: InputMethodManager = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(facebookAccount.editText, 0)
        }
        familyNameInLaw.apply {
            isEnabled = isEditable
        }
        facebookAccount.apply {
            isEnabled = isEditable
        }
        /*mTvPersonalInfoFacebookId = view.find(R.id.tv_personal_info_facebook_id)
        mTvPersonalInfoFacebookId.apply {
            isClickable = isEditable
        }*/
/*        fullName = view.find(R.id.id_edittext_personal_info_fullname)
        ktpno = view.find(R.id.id_edittext_personal_info_ktp_no)
        gender = view.find(R.id.id_textview_persoanl_info_gender)*/
//        gender.onClick { setGender() }
        education = view.find(R.id.id_textview_personal_info_education)
        education.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.PERSONAL_EDUCATION, null)
                setEducation() }
            isClickable = isEditable
        }
        marital = view.find(R.id.id_textview_personal_info_marital_status)
        marital.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.PERSONAL_MARRIAGE, null)
                setMarital() }
            isClickable = isEditable
        }
        childrenAccount = view.find(R.id.id_textview_personal_info_number_of_children)
        childrenAccount.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.PERSONAL_CHLIDREN, null)
                setChildrenAccount() }
            isClickable = isEditable
        }
        region = view.find(R.id.id_textview_personal_info_region)
        region.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.PERSONAL_RESIDENCE_ADDRESS, null)
                getRegion() }
            isClickable = isEditable
        }
        address = view.find(R.id.id_edittext_personal_onfo_address)
        address.apply {
            isEnabled = isEditable
        }
        address.setItemOnClickListener {
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.PERSONAL_FULL_ADDRESS, null)
            val imm: InputMethodManager = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(address.editText, 0)
        }
        duration = view.find(R.id.id_textview_personal_info_duration)
        duration.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.PERSONAL_RESIDENCE_ADDRESS_DURATION, null)
                setDuration() }
            isClickable = isEditable
        }
        pInfoSummit = view.find(R.id.id_button_personal_info_submit)
        pInfoSummit.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_PERSONAL_INFO_SUBMIT, null)

                personalInfoSubmit()
            }
        }
        pInfoSummit.setOnTouchListener { v, event ->
            if (!pInfoSummit.isClickable) {
                val ret = checkUnFillContent()
                if (!TextUtils.isEmpty(ret)) {
                    ret?.let {
                        XLeoToast.makeText(context, ret, Toast.LENGTH_SHORT).show()
                    }
                }
            }
            return@setOnTouchListener false
        }
        changeMarkPosition(view)
    }

    private var stepViewVisible: Boolean = true

    fun setStepViewGone() {
        stepViewVisible = false
    }

    private var stepView: HorizontalStepView? = null
    /**
     * 设置StepView节点状态
     * @param i 当前步骤
     */
    private fun changeMarkPosition(view: View) {
        stepView = view.find(R.id.step_view)

        if (!stepViewVisible) {
            stepView!!.visibility = GONE
            return
        }

        val stepsBeanList = java.util.ArrayList<StepBean>()
        val stepBean0 = StepBean("Identification", StepBean.STEP_COMPLETED)
        val stepBean1 = StepBean("Personal Info", StepBean.STEP_CURRENT)
        val stepBean2 = StepBean("Contact Info", StepBean.STEP_UNDO)
        val stepBean3 = StepBean("Job Info", StepBean.STEP_UNDO)
        stepsBeanList.add(stepBean0)
        stepsBeanList.add(stepBean1)
        stepsBeanList.add(stepBean2)
        stepsBeanList.add(stepBean3)

        stepView!!.setStepViewTexts(stepsBeanList)
    }

    private fun getRegion() {
        (mActivity as PersonalInfoActivity).forwardToNextFragment(null)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        if (!hidden) {
            handleRegionChange()
        }
    }

    private fun handleRegionChange() {
        val regionDatas = HashMap<String, RegionBean.RegionsBean>()
        val level = (mActivity as PersonalInfoActivity).getRegionDatas(regionDatas)
        when (level) {
            RegionLevel.province.ordinal -> {
                val province = regionDatas[RegionLevel.province.toString()]
                if (personalInfoBean.province?.id != province!!.id) {
                    personalInfoBean.province = province
                    /*personalInfoBean.area = null*/
                    personalInfoBean.district = null
                    personalInfoBean.city = null
                    personalInfoBean.address = null
                }
            }
            RegionLevel.city.ordinal -> {
                val province = regionDatas[RegionLevel.province.toString()]
                val city = regionDatas[RegionLevel.city.toString()]
                if (personalInfoBean.province?.id != province!!.id) {
                    personalInfoBean.province = province
                    personalInfoBean.city = city
                    /*personalInfoBean.area = null*/
                    personalInfoBean.district = null
                    personalInfoBean.address = null
                } else if (personalInfoBean.city?.id != city!!.id) {
                    personalInfoBean.city = city
                    /*personalInfoBean.area = null*/
                    personalInfoBean.district = null
                    personalInfoBean.address = null
                }
            }
            RegionLevel.district.ordinal -> {
                val province = regionDatas[RegionLevel.province.toString()]
                val city = regionDatas[RegionLevel.city.toString()]
                val district = regionDatas[RegionLevel.district.toString()]
                when {
                    personalInfoBean.province?.id != province!!.id -> {
                        personalInfoBean.province = province
                        personalInfoBean.city = city
                        /*personalInfoBean.area = null*/
                        personalInfoBean.district = district
                        personalInfoBean.address = null
                    }
                    personalInfoBean.city?.id != city!!.id -> {
                        personalInfoBean.city = city
                        /*personalInfoBean.area = null*/
                        personalInfoBean.district = district
                        personalInfoBean.address = null
                    }
                    personalInfoBean.district?.id != district!!.id -> {
                        /*personalInfoBean.area = null*/
                        personalInfoBean.district = district
                        personalInfoBean.address = null
                    }
                }
            }
            /*RegionLevel.area.ordinal -> {
                val province = regionDatas[RegionLevel.province.toString()]
                val city = regionDatas[RegionLevel.city.toString()]
                val district = regionDatas[RegionLevel.district.toString()]
                val area = regionDatas[RegionLevel.area.toString()]
                when {
                    personalInfoBean.province?.id != province!!.id -> {
                        personalInfoBean.province = province
                        personalInfoBean.city = city
                        personalInfoBean.area = area
                        personalInfoBean.district = district
                        personalInfoBean.address = null
                    }
                    personalInfoBean.city?.id != city!!.id -> {
                        personalInfoBean.city = city
                        personalInfoBean.area = area
                        personalInfoBean.district = district
                        personalInfoBean.address = null
                    }
                    personalInfoBean.district?.id != district!!.id -> {
                        personalInfoBean.area = area
                        personalInfoBean.district = district
                        personalInfoBean.address = null
                    }
                    personalInfoBean.area.id != area!!.id -> {
                        personalInfoBean.area = area
                        personalInfoBean.address = null
                    }
                }
            }*/
            else -> {
                throw IllegalArgumentException("wrong argument of region datas")
            }
        }
        updateRegionInfo()
    }

    @SuppressLint("SetTextI18n")
    private fun updateRegionInfo() {
        if (personalInfoBean.province != null
                && personalInfoBean.city != null
                && personalInfoBean.district != null
        /*&& personalInfoBean.area != null*/) {
            region.text = personalInfoBean.province?.name + "-" + personalInfoBean.city?.name + "-" + personalInfoBean.district?.name/* + "-" + personalInfoBean.area?.name*/
        }

        address.text = personalInfoBean.address
        updateSubmitSate()
    }

    var notFinish: Boolean = false
    var fromSplash: Boolean = false
    override fun initData() {
        if (mActivity.intent.getBooleanExtra(FieldParams.NOT_FINISH_CERTIFY, false)) {
            notFinish = true
        }
        if (mActivity.intent.getBooleanExtra(FieldParams.FROM_SPLASH, false)) {
            fromSplash = true
        }
        if (hasSavedState) {
            hasSavedState = false
        } else {
            mPresenter.obtainInitDatas()
        }
    }

    @SuppressLint("SetTextI18n")
    override fun reinitView(personalInfoServerBean: PersonalInfoServerBean) {
        if (personalInfoServerBean != null) {
            mServerInfo = PersonalInfoBean(personalInfoServerBean)
        }
        personalInfoBean = PersonalInfoBean(personalInfoServerBean)
        fullName = personalInfoBean.fullName
        firstName = personalInfoBean.firstName
        middleName = personalInfoBean.middleName
        lastName = personalInfoBean.lastName
        birthday = personalInfoBean.birthday
        cardType = personalInfoBean.credentialType
        ktpno = personalInfoBean.credentialNo
        familyNameInLaw.setText(personalInfoBean.familyNameInLaw)
        facebookAccount.text = personalInfoBean.facebookId
        gender = getString(GenderStatus.valueOf(personalInfoBean.gender).showString)
        education.text = personalInfoBean.lastEducation
        marital.text = getString(MarriageStatus.valueOf(personalInfoBean.maritalStatus).showString)
        childrenAccount.text = getString(ChildrenNumStatus.valueOf(personalInfoBean.childrenNumber).showString)
        region.text = personalInfoBean.province.name + "-" + personalInfoBean.city.name + "-" + personalInfoBean.district.name /*+ "-" + personalInfoBean.area.name*/
        address.text = personalInfoBean.address
        if (!TextUtils.isEmpty(personalInfoBean.residenceDuration)) {
            duration.text = getString(DurationStatus.valueOf(personalInfoBean.residenceDuration).showString)
        }
        /*if (personalInfoBean.facebookId != null) {
            mTvPersonalInfoFacebookId.text = personalInfoBean.facebookId
        }*/
        initByLocal()
        updateSubmitSate()
        if (arguments != null) {
            val any = arguments!![FieldParams.NEED_UPDATE_REGION]
            if (any != null && any as Boolean) {
                handleRegionChange()
                arguments!!.putBoolean(FieldParams.NEED_UPDATE_REGION, false)
            }
        }
    }

    private fun editTextChangeEvent() {
        /*val observableFullName = RxTextView.textChanges(fullName)
        val observableFullKtp = RxTextView.textChanges(ktpno)*/
        val observableFullAddress = RxTextView.textChanges(address.editText)
        val observableFacebookId = RxTextView.textChanges(facebookAccount.editText)

        /*val observableFullFamilyNameInlaw = RxTextView.textChanges(familyNameInLaw)*/


//        Observable.combineLatest(observableFullName, observableFullAddress, observableFullKtp, observableFacebookId) { charSequence, charSequence2, charSequence3, charSequence4 -> !TextUtils.isEmpty(charSequence.toString()) || !TextUtils.isEmpty(charSequence2.toString()) || !TextUtils.isEmpty(charSequence3.toString()) || !TextUtils.isEmpty(charSequence4.toString()) }.subscribe { updateSubmitSate() }
        Observable.combineLatest(observableFullAddress, observableFacebookId) { charSequence2,
                                                                                charSequence4 ->
            !TextUtils.isEmpty(charSequence2.toString()) || !TextUtils.isEmpty(charSequence4.toString())
        }.subscribe { updateSubmitSate() }
    }


    /**
     * Set  gender adapter
     */
    private fun getGenderAdapter(): InfoAdapter {
        val genderAdapter = InfoAdapterEnum(context)
        genderAdapter.addItem(GenderStatus.MALE, InfoType.GENDER)
        genderAdapter.addItem(GenderStatus.FEMALE, InfoType.GENDER)
        genderAdapter.setOnItemClickListener(object : OnInfoAdapterItemClickListener {
            override fun onItemClick(data: InfoAdapter.InfoItem) {
                if (dialogPlus.isShowing) {
                    dialogPlus.dismiss()
                }
                gender = data.infoStr
                personalInfoBean.gender = data.valueStr
                updateSubmitSate()
            }

        })

        return genderAdapter

    }

    override fun onDurationSelected(data: InfoAdapter.InfoItem) {
        if (dialogPlus.isShowing) {
            dialogPlus.dismiss()
        }
        duration.text = data.infoStr
        personalInfoBean.residenceDuration = data.valueStr
        updateSubmitSate()
    }

    /**
     * Set marital status
     */
    private fun getMaritalStatusAdapter(): InfoAdapter {
        val maritalAdapter = InfoAdapterEnum(context)
        maritalAdapter.addItem(MarriageStatus.SINGLE, InfoType.MATRIAL)
        maritalAdapter.addItem(MarriageStatus.MARRIED, InfoType.MATRIAL)
        maritalAdapter.addItem(MarriageStatus.DIVORCED, InfoType.MATRIAL)
        maritalAdapter.addItem(MarriageStatus.WIDOWED, InfoType.MATRIAL)
        maritalAdapter.setOnItemClickListener(object : OnInfoAdapterItemClickListener {
            override fun onItemClick(data: InfoAdapter.InfoItem) {
                if (dialogPlus.isShowing) {
                    dialogPlus.dismiss()
                }
                marital.text = data.infoStr
                personalInfoBean.maritalStatus = data.valueStr
                updateSubmitSate()
            }

        })
        return maritalAdapter
    }

    /**
     * Set children number
     */
    private fun getChildrenAccountAdapter(): InfoAdapter {
        val childrenAccountAdapter = InfoAdapterEnum(context)
        childrenAccountAdapter.addItem(ChildrenNumStatus.ZERO, InfoType.CHILDREN)
        childrenAccountAdapter.addItem(ChildrenNumStatus.ONE, InfoType.CHILDREN)
        childrenAccountAdapter.addItem(ChildrenNumStatus.TWO, InfoType.CHILDREN)
        childrenAccountAdapter.addItem(ChildrenNumStatus.THREE, InfoType.CHILDREN)
        childrenAccountAdapter.addItem(ChildrenNumStatus.FOUR, InfoType.CHILDREN)
        childrenAccountAdapter.addItem(ChildrenNumStatus.OVER_FOUR, InfoType.CHILDREN)
        childrenAccountAdapter.setOnItemClickListener(object : OnInfoAdapterItemClickListener {
            override fun onItemClick(data: InfoAdapter.InfoItem) {
                if (dialogPlus.isShowing) {
                    dialogPlus.dismiss()
                }
                childrenAccount.text = data.infoStr
                personalInfoBean.childrenNumber = data.valueStr
                updateSubmitSate()
            }
        })
        return childrenAccountAdapter
    }


    private fun updateSubmitSate() {
        if (isCheckedField() && isEditable) {
            pInfoSummit.isClickable = true
            pInfoSummit.isSelected = false
        } else {
            pInfoSummit.isClickable = false
            pInfoSummit.isSelected = true
        }
    }

    private fun isCheckedField(): Boolean {
        if (TextUtils.isEmpty(fullName)) {
            //XLeoToast.showMessage(getStringById(R.string.show_input_fullname));
            return false
        }
        if (TextUtils.isEmpty(ktpno)) {
            //XLeoToast.showMessage(getStringById(R.string.show_input_ktp_no));
            return false
        }
        /*if (!familyNameInLaw.checkLegal() || TextUtils.getTrimmedLength(familyNameInLaw.text) <= 0) {
            //XLeoToast.showMessage(getStringById(R.string.show_input_ktp_no));
            return false
        }*/

        if (TextUtils.isEmpty(gender)) {
            //XLeoToast.showMessage(getStringById(R.string.show_input_gender));
            return false
        }
        if (TextUtils.isEmpty(education.text.toString())) {
            //XLeoToast.showMessage(getStringById(R.string.show_input_education));
            return false
        }
        if (TextUtils.isEmpty(marital.text.toString())) {
            //XLeoToast.showMessage(getStringById(R.string.show_input_marital));
            return false
        }
        if (TextUtils.isEmpty(childrenAccount.text.toString())) {
            //XLeoToast.showMessage(getStringById(R.string.show_input_account));
            return false
        }

        if (personalInfoBean.province?.name == null) {
            //XLeoToast.showMessage(getStringById(R.string.show_input_province));
            return false
        }
        if (personalInfoBean.city?.name == null) {
            //XLeoToast.showMessage(getStringById(R.string.show_input_city));
            return false
        }
        if (personalInfoBean.district?.name == null) {
            // XLeoToast.showMessage(getStringById(R.string.show_input_street));
            return false
        }
        /*if (personalInfoBean.area?.name == null) {
            //XLeoToast.showMessage(getStringById(R.string.show_input_area));
            return false
        }*/

        if (!address.checkLegal() || TextUtils.getTrimmedLength(address.text) <= 0) {
            //XLeoToast.showMessage(getStringById(R.string.show_input_address));
            return false
        }

        if (TextUtils.isEmpty(facebookAccount.text.toString())) {
            //XLeoToast.showMessage(getStringById(R.string.show_input_area));
            return false
        }

        return true/*!TextUtils.isEmpty(duration.text.toString())*/
    }

    fun setFacebookId() {
//        startActivityForResult(Intent(context, CheckInFacebookActivity::class.java), mRequestCode)
    }


    fun setGender() {
        val genderAdapter = getGenderAdapter() as InfoAdapterEnum
        dialogPlus = DialogManager.newListViewDialog(context)
                .setAdapter(genderAdapter)
                .setExpanded(false)
                .setGravity(Gravity.CENTER)
                .create()
        dialogPlus.show()
    }

    private fun setEducation() {
        mPresenter.requestEducation()
    }


    private fun setMarital() {
        val maritalAdapter = getMaritalStatusAdapter() as InfoAdapterEnum
        dialogPlus = DialogManager.newListViewDialog(context)
                .setAdapter(maritalAdapter)
                .setExpanded(false)
                .setGravity(Gravity.CENTER)
                .create()
        dialogPlus.show()
    }


    private fun setChildrenAccount() {
        val childrenAccountAdapter = getChildrenAccountAdapter() as InfoAdapterEnum
        dialogPlus = DialogManager.newListViewDialog(context)
                .setAdapter(childrenAccountAdapter)
                .setExpanded(false)
                .setGravity(Gravity.CENTER)
                .create()
        dialogPlus.show()
    }

    private fun setDuration() {
        val durationAdapter = mPresenter.getDurationAdapter() as InfoAdapterEnum
        dialogPlus = DialogManager.newListViewDialog(context)
                .setAdapter(durationAdapter)
                .setExpanded(false)
                .setGravity(Gravity.CENTER)
                .create()
        dialogPlus.show()
    }

    private fun personalInfoSubmit() {
        if (isCheckedField()) {
            mActivity.showLoading(resources.getText(R.string.show_uploading).toString())
            personalInfoBean.fullName = fullName
            personalInfoBean.firstName = firstName
            personalInfoBean.middleName = middleName
            personalInfoBean.lastName = lastName
            personalInfoBean.birthday = birthday
            personalInfoBean.credentialType = cardType

            personalInfoBean.familyNameInLaw = familyNameInLaw.text.toString()
            personalInfoBean.facebookId = facebookAccount.text.toString()
            personalInfoBean.credentialNo = ktpno
            personalInfoBean.address = address.text.toString().trim({ it <= ' ' })
            mPresenter.uploadDatas(personalInfoBean)
        }
    }

    override fun onAddressesObtain(addresses: List<Address>) {
        if (addresses.isNotEmpty()) {
            val sb = StringBuffer()
            //            for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex() - 1; i++) {
            //                sb.append(addresses.get(0).getAddressLine(i) + "-");
            //            }
            //            sb.append(addresses.get(0).getAddressLine(addresses.get(0).getMaxAddressLineIndex()));
            val address = addresses[0]
            sb.append(address.countryName + "-")
            sb.append(address.adminArea + "-")
            if (!TextUtils.isEmpty(address.subAdminArea)) {
                sb.append(address.subAdminArea + "-")
            }
            if (!TextUtils.isEmpty(address.locality)) {
                sb.append(address.locality + "-")
            }
            if (!TextUtils.isEmpty(address.subLocality)) {
                sb.append(address.subLocality + "-")
            }
            if (!TextUtils.isEmpty(address.thoroughfare)) {
                sb.append(address.thoroughfare + "-")
            }
            if (!TextUtils.isEmpty(address.subThoroughfare)) {
                sb.append(address.subThoroughfare)
            }
            XLog.d("address" + addresses[0].getAddressLine(0), 10)
            this.address.text = sb.toString()
        } else {
            XLeoToast.showMessage(R.string.tips4inputaddress)
        }
    }

    override fun responseEducation(sysDictBeanList: ArrayList<SysDictBean>) {
        val educationAdapter = EducationListAdapter(sysDictBeanList, object : EducationListAdapter.OnEducationItemClickListener {
            override fun onItemClick(sysDictBean: SysDictBean) {
                if (dialogPlus.isShowing) {
                    dialogPlus.dismiss()
                }
                education.text = sysDictBean.value
                personalInfoBean.lastEducation = sysDictBean.value
                updateSubmitSate()
            }
        })
        dialogPlus = DialogManager.newListViewDialog(context)
                .setAdapter(educationAdapter)
                .setExpanded(false)
                .setGravity(Gravity.CENTER)
                .create()
        dialogPlus.show()
    }

    override fun responseEducationEmpty() {
        XLeoToast.showMessage(R.string.empty_education)
    }

    override fun responseEducationError(message: String?) {
        XLeoToast.showMessage(message)
    }

    private fun checkUnFillContent(): String? {
        if (TextUtils.isEmpty(familyNameInLaw.text) || !familyNameInLaw.checkLegal()) {
            if (familyNameInLaw.text?.toString()?.length ?: 0 > 64) {
                return getString(R.string.mother_name_too_long)
            }
        }
        /*if (TextUtils.isEmpty(education.text)) {
            return getString(R.string.enter_education)
        }*/
        if (!education.checkLegal()) {
            return null
        }
        /*if (TextUtils.isEmpty(facebookAccount.text)) {
            return getString(R.string.enter_facebook_id)
        }*/
        /*if (TextUtils.isEmpty(marital.text)) {
            return getString(R.string.enter_married_status)
        }*/
        if (!marital.checkLegal()) {
            return null
        }
        /*if (TextUtils.isEmpty(childrenAccount.text)) {
            return getString(R.string.enter_children_count)
        }*/
        if (!childrenAccount.checkLegal()) {
            return null
        }
        /*if (TextUtils.isEmpty(region.text)) {
            return getString(R.string.enter_region)
        }*/
        if (!region.checkLegal()) {
            return null
        }
        if (TextUtils.isEmpty(address.text)) {
            return null
            /*return if (address.text?.toString()?.length ?: 0 > 256) {
                getString(R.string.address_too_long)
            } else {
                getString(R.string.enter_address)
            }*/
        } else if (!address.checkLegal() && address.text?.toString()?.length ?: 0 > 256) {
            return getString(R.string.address_too_long)
        }

        if (!facebookAccount.checkLegal()) {
            return null
        }
        return null
    }


    private fun localInputExist(): Boolean {
        return !TextUtils.isEmpty(education.text.toString())
                || !TextUtils.isEmpty(marital.text.toString())
                || !TextUtils.isEmpty(childrenAccount.text.toString())
                || !TextUtils.isEmpty(region.text.toString())
                || !TextUtils.isEmpty(address.text.toString())
                || !TextUtils.isEmpty(duration.text.toString())
                || !TextUtils.isEmpty(familyNameInLaw.text.toString())
    }

    var mServerInfo: PersonalInfoBean? = null

    /**检查本地输入是否和服务器的相同*/
    private fun identicalToServer(): Boolean {

        //都相同，返回true
        if (mServerInfo != null) {

            val serverArr = arrayOf(
                    mServerInfo?.familyNameInLaw,
                    mServerInfo?.province?.name,
                    mServerInfo?.city?.name,
                    mServerInfo?.district?.name,
                    /*mServerInfo?.area?.name,*/
                    mServerInfo?.address,
                    mServerInfo?.lastEducation,
                    mServerInfo?.maritalStatus,
                    mServerInfo?.childrenNumber,
                    mServerInfo?.residenceDuration,
                    mServerInfo?.facebookId
            )

            val localArr = getLocalInput()

            return serverArr contentEquals localArr
        } else {
            return false
        }
    }

    private fun getLocalInput(): Array<String?> {
        return arrayOf(
                familyNameInLaw.text.toString(),
                personalInfoBean.province?.name,
                personalInfoBean.city?.name,
                personalInfoBean.district?.name,
                /*personalInfoBean.area?.name,*/
                address.text.toString(),
                personalInfoBean.lastEducation,
                personalInfoBean.maritalStatus,
                personalInfoBean.childrenNumber,
                personalInfoBean.residenceDuration,
                personalInfoBean.facebookId
        )
    }

    private fun saveLocalInput() {
        val cache = ACache.get(this.baseActivity)

        if (!TextUtils.isEmpty(familyNameInLaw.text.toString())) {
            cache.put(getSaveKey(FieldParams.PersonInfo.FAMILYNAMEINLAW), familyNameInLaw.text.toString())
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.FAMILYNAMEINLAW))
        }

        if (!TextUtils.isEmpty(facebookAccount.text.toString())) {
            cache.put(getSaveKey(FieldParams.PersonInfo.FACEBOOK_ID), facebookAccount.text.toString())
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.FACEBOOK_ID))
        }

        if (!TextUtils.isEmpty(personalInfoBean.lastEducation)) {
            cache.put(getSaveKey(FieldParams.PersonInfo.EDUCATION), personalInfoBean.lastEducation)
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.EDUCATION))
        }

        if (!TextUtils.isEmpty(personalInfoBean.maritalStatus)) {
            cache.put(getSaveKey(FieldParams.PersonInfo.MARITAL), personalInfoBean.maritalStatus)
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.MARITAL))
        }

        if (!TextUtils.isEmpty(personalInfoBean.childrenNumber)) {
            cache.put(getSaveKey(FieldParams.PersonInfo.CHILDRENACCOUNT), personalInfoBean.childrenNumber)
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.CHILDRENACCOUNT))
        }

//        if(!TextUtils.isEmpty(region.text.toString())){
//            cache.put(getSaveKey(FieldParams.PersonInfo.REGION), region.text.toString())
//        }else{
//            cache.remove(getSaveKey(FieldParams.PersonInfo.REGION))
//        }

        if (!TextUtils.isEmpty(personalInfoBean.province?.name)) {
            cache.put(getSaveKey(FieldParams.PersonInfo.PROVINCE), personalInfoBean.province.name)
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.PROVINCE))
        }

        if (!TextUtils.isEmpty(personalInfoBean.city?.name)) {
            cache.put(getSaveKey(FieldParams.PersonInfo.CITY), personalInfoBean.city.name)
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.CITY))
        }

        if (!TextUtils.isEmpty(personalInfoBean.district?.name)) {
            cache.put(getSaveKey(FieldParams.PersonInfo.DISTRICT), personalInfoBean.district.name)
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.DISTRICT))
        }

        /*if (!TextUtils.isEmpty(personalInfoBean.area?.name)) {
            cache.put(getSaveKey(FieldParams.PersonInfo.AREA), personalInfoBean.area.name)
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.AREA))
        }*/

        if (!TextUtils.isEmpty(address.text.toString())) {
            cache.put(getSaveKey(FieldParams.PersonInfo.ADDRESS), address.text.toString())
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.ADDRESS))
        }

        if (!TextUtils.isEmpty(personalInfoBean.residenceDuration)) {
            cache.put(getSaveKey(FieldParams.PersonInfo.DURATION), personalInfoBean.residenceDuration)
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.DURATION))
        }
    }

    private fun removeThisPageLocal() {
        val cache = ACache.get(this.baseActivity)
        cache.remove(getSaveKey(FieldParams.PersonInfo.EDUCATION))
        cache.remove(getSaveKey(FieldParams.PersonInfo.MARITAL))
        cache.remove(getSaveKey(FieldParams.PersonInfo.CHILDRENACCOUNT))

        cache.remove(getSaveKey(FieldParams.PersonInfo.PROVINCE))
        cache.remove(getSaveKey(FieldParams.PersonInfo.CITY))
        cache.remove(getSaveKey(FieldParams.PersonInfo.DISTRICT))
        cache.remove(getSaveKey(FieldParams.PersonInfo.AREA))

        cache.remove(getSaveKey(FieldParams.PersonInfo.ADDRESS))
        cache.remove(getSaveKey(FieldParams.PersonInfo.DURATION))
        cache.remove(getSaveKey(FieldParams.PersonInfo.DURATION))
        cache.remove(getSaveKey(FieldParams.PersonInfo.FACEBOOK_ID))

    }

    private fun removeAllLocal() {
        val cache = ACache.get(this.baseActivity)

        cache.remove(getSaveKey(FieldParams.PersonInfo.FULLNAME))
        cache.remove(getSaveKey(FieldParams.PersonInfo.KTP_NO))
        cache.remove(getSaveKey(FieldParams.PersonInfo.GENDER))

        removeThisPageLocal()
    }

    private fun getSaveKey(key: String): String {
        return key + TokenManager.getInstance().mobile
    }
}

class PersonalInfoPresenterImpl : PersonalInfoPresenter, BaseFragmentPresenterImpl() {

    private var educationSysDictBeanList: ArrayList<SysDictBean>? = null

    override fun requestEducation() {
        if (educationSysDictBeanList == null) {
            showLoading("")
            mUserApi.sysDict(SysDict.Type.EDUCATION.name)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(mView.bindToLifecycle())
                    .subscribe(object : Subscriber<ArrayList<SysDictBean>>() {
                        override fun onNext(t: ArrayList<SysDictBean>?) {
                            dismissLoading()
                            if (t == null || t.isEmpty()) {
                                (mView as PersonalInfoView).responseEducationEmpty()
                            } else {
                                educationSysDictBeanList = t
                                (mView as PersonalInfoView).responseEducation(t)
                            }
                        }

                        override fun onCompleted() {
                        }

                        override fun onError(e: Throwable?) {
                            e?.printStackTrace()
                            dismissLoading()
                            (mView as PersonalInfoView).responseEducationError(e?.message)
                        }

                    })
        } else {
            if (educationSysDictBeanList == null || educationSysDictBeanList!!.isEmpty()) {
                (mView as PersonalInfoView).responseEducationEmpty()
            } else {
                (mView as PersonalInfoView).responseEducation(educationSysDictBeanList!!)
            }
        }
    }

    /**
     * Set duration
     */
    override fun getDurationAdapter(): InfoAdapter {
        val areaAdapter = InfoAdapterEnum(mView.baseActivity)
        areaAdapter.addItem(DurationStatus.THREE_MONTH, InfoType.DURATION)
        areaAdapter.addItem(DurationStatus.SIX_MONTH, InfoType.DURATION)
        areaAdapter.addItem(DurationStatus.ONE_YEAR, InfoType.DURATION)
        areaAdapter.addItem(DurationStatus.TWO_YEAR, InfoType.DURATION)
        areaAdapter.addItem(DurationStatus.OVER_TWO_YEAR, InfoType.DURATION)
        areaAdapter.setOnItemClickListener(object : OnInfoAdapterItemClickListener {
            override fun onItemClick(data: InfoAdapter.InfoItem) {
                if (isAttached) {
                    (mView as PersonalInfoView).onDurationSelected(data)
                }
            }
        })
        return areaAdapter
    }

    override fun uploadDatas(personalInfoBean: PersonalInfoBean) {
        mUserApi.submitPersonalInfo(personalInfoBean.firstName,
                personalInfoBean.middleName,
                personalInfoBean.lastName,
                personalInfoBean.fullName,
                personalInfoBean.credentialType,
                personalInfoBean.birthday,
                personalInfoBean.credentialNo, personalInfoBean.familyNameInLaw, personalInfoBean.gender, personalInfoBean.province.name, personalInfoBean.city.name, personalInfoBean.district.name, /*personalInfoBean.area.name*/"", personalInfoBean.address, personalInfoBean.lastEducation, personalInfoBean.maritalStatus, personalInfoBean.childrenNumber, personalInfoBean.residenceDuration, personalInfoBean.facebookId, TokenManager.getInstance().token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Subscriber<ResponseBody>() {
                    override fun onCompleted() {

                    }

                    override fun onError(e: Throwable) {
                        dismissLoading()
                        if (e is HttpException) {
                            try {
                                val responseErrorBody = Gson().fromJson(e.response()?.errorBody()?.string(), ResponseErrorBody::class.java)
                                XLeoToast.showMessage("" + responseErrorBody?.message)
                            } catch (e: Throwable) {
                                XLeoToast.showMessage(R.string.error_occured)
                            }
                        } else {
                            XLeoToast.showMessage(e.message)
                        }
                        XLog.e("e:", e, 100)

                    }

                    override fun onNext(responseBody: ResponseBody) {
                        (mView as PersonalInfoView).onUploadedSuccess()
                        if (!isAttached) {
                            return
                        }
                        mView.baseActivity.setResult(Activity.RESULT_OK)
                        mView.baseActivity.dismissLoading()
                        mView.baseActivity.startActivity(Intent(mView.baseActivity, ContactInfoActivity::class.java).putExtra(FieldParams.NOT_FINISH_CERTIFY, !(mView as PersonalInfoView).finish()))
                        if ((mView as PersonalInfoView).finish()) {
                            mView.baseActivity.finish()
                        }
                        XLog.d("Submit success!", 10)
                    }
                })
    }

    private var hasObtain: Boolean = false
    override fun obtainInitDatas() {
        if (hasObtain) {
            return
        }
        if (isAttached) {
            showLoading(null)
            mUserApi.getPersonalInfo(TokenManager.getInstance().token)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Subscriber<PersonalInfoServerBean>() {
                        override fun onCompleted() {

                        }

                        override fun onError(e: Throwable) {
                            dismissLoading()
                            XLog.e("Get Personalinfo failed: ", e, 100)
                            XLeoToast.showMessage(R.string.show_get_personalinfo_failed)
                        }

                        override fun onNext(personalInfoServerBean: PersonalInfoServerBean?) {
                            dismissLoading()
                            hasObtain = true
                            if (isAttached && personalInfoServerBean != null) {
                                (mView as PersonalInfoView).reinitView(personalInfoServerBean)
                            }
                        }
                    })
        }
    }

}

interface PersonalInfoView {
    fun reinitView(personalInfoServerBean: PersonalInfoServerBean)
    fun onAddressesObtain(addresses: List<Address>)
    fun onDurationSelected(data: InfoAdapter.InfoItem)
    fun responseEducation(sysDictBeanList: ArrayList<SysDictBean>)
    fun responseEducationEmpty()
    fun responseEducationError(message: String?)
    fun onUploadedSuccess()
    fun finish(): Boolean
}

interface PersonalInfoPresenter : BaseFragmentPresenter {
    fun obtainInitDatas()
    fun uploadDatas(personalInfoBean: PersonalInfoBean)
    fun getDurationAdapter(): InfoAdapter
    fun requestEducation()
}

interface OnInfoAdapterItemClickListener {
    fun onItemClick(data: InfoAdapter.InfoItem)
}

class EducationListAdapter(private val sysDictBeanList: ArrayList<SysDictBean>?, private val onEducationItemClickListener: EducationListAdapter.OnEducationItemClickListener) : BaseAdapter() {

    override fun getCount(): Int {
        return sysDictBeanList?.size ?: 0
    }

    override fun getItem(position: Int): SysDictBean {
        return sysDictBeanList!![position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
        var itemView = convertView
        if (convertView == null) {
            itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_dialog_list, parent, false)
        }
        with(getItem(position)) {
            itemView?.find<TextView>(R.id.id_textview_bank_item)?.text = value
            itemView?.setOnClickListener {
                onEducationItemClickListener.onItemClick(this)
            }
        }

        return itemView
    }

    fun dataChanged(sysDictBeanList: List<SysDictBean>) {
        this.sysDictBeanList?.clear()
        this.sysDictBeanList?.addAll(sysDictBeanList)

        this.notifyDataSetChanged()
    }

    interface OnEducationItemClickListener {
        fun onItemClick(sysDictBean: SysDictBean)
    }
}